from django.forms import ModelForm
from django.forms import widgets as wid
from django.core.exceptions import ValidationError
from django import forms
from aj import models
import re
sxs=models.Xingzhengquhua.objects.values_list('shi','shi').distinct()
# 机构队伍管理

class Regist_form(ModelForm):
    password = forms.CharField(label="登陆密码",widget=wid.Input({'placeholder':'八位以上字母数字混合密码'}))
    xzqh=forms.ChoiceField(
        label="省辖市",
        choices=sxs,
        widget=forms.widgets.Select()
    )

    class Meta:
        # fields = '__all__'
        fields=['name','phone','organization','xueli','junren','falv','zfz','bzlx','gzbz','sfzhm']
        model = models.UserInfo
    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
    def clean_phone(self):
        tel=self.cleaned_data.get("phone")
        ret = re.match(r"^1[35678]\d{9}$", tel)
        if not ret:
            raise ValidationError("手机号码格式不正确")
        return tel

    def clean_sfzhm(self):
        sfzhm=self.cleaned_data.get("sfzhm")
        ret = re.match(r"^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$", sfzhm)
        if not ret:
            raise ValidationError("身份证号码格式不正确")
        return sfzhm
    def clean_password(self):
        password=self.cleaned_data.get("password")
        ret = re.match(r"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$", password)
        if not ret:
            raise ValidationError("八位以上字母数字混合密码")
        return password

class Organization_form(ModelForm):
    class Meta:
        # fields = '__all__'
        exclude=['xingzhengquhua','sj']
        model = models.Organization
    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
    def clean(self):
        phone1 = self.cleaned_data.get('phone1')
        phone2 = self.cleaned_data.get('phone2')
        bianzhi = self.cleaned_data.get('bianzhi')
        dwxz = self.cleaned_data.get('dwxz')
        che = self.cleaned_data.get('che')
        jingfei = self.cleaned_data.get('jingfei')
        data=(('phone1',phone1),('phone2',phone2),('bianzhi',bianzhi),('dwxz',dwxz),('che',che),('jingfei',jingfei),)
        for i in data:
            if i[1]==None:
                self.add_error(i[0], '这个字段是必填项')
        return self.cleaned_data
